<?php
/**
 * WithdrawService.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-06-01 10:12:57
 * @modified   2023-06-01 10:12:57
 */

namespace Beike\Seller\Services;

use Beike\Seller\Repositories\SellerTransactionRepo;
use Beike\Seller\Repositories\WithdrawRepo;
use Illuminate\Support\Facades\DB;

class WithdrawService
{
    /**
     * @param float $amount
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     * @throws \Exception
     */
    public static function create(float $amount)
    {
        if ($amount < 0) {
            throw new \Exception(trans('seller::withdraw.withdraw_amount_error'));
        }
        $seller  = current_seller_user()->seller;
        $balance = SellerTransactionRepo::getBalance($seller->id);
        if ($amount > $balance) {
            throw new \Exception(trans('seller::withdraw.balance_not_enough'));
        }
        $data = [
            'seller_id'     => $seller->id,
            'bank'          => $seller->bank,
            'bank_account'  => $seller->bank_account,
            'bank_name'     => $seller->bank_name,
            'currency_code' => system_setting('base.currency'),
            'amount'        => $amount,
            'description'   => '',
            'status'        => 0,
        ];

        try {
            DB::beginTransaction();

            $withdraw = WithdrawRepo::create($data);

            SellerTransactionRepo::create([
                'seller_id'   => $seller->id,
                'withdraw_id' => $withdraw->id,
                'amount'      => -$amount,
                'description' => 'withdraw',

            ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            throw $e;
        }

        return $withdraw;
    }

    /**
     * @param $id
     * @param $paid
     * @param $comment
     * @return void
     * @throws \Throwable
     */
    public static function process($id, $paid, $comment)
    {
        $withdraw              = WithdrawRepo::find($id);
        $withdraw->status      = 1;
        $withdraw->description = $comment;
        if ($paid) {
            $withdraw->paid_at = now();
        }

        $withdraw->saveOrFail();

        if (! $paid) {
            SellerTransactionRepo::deleteByWithdrawId($id);
        }
    }
}
